package threadSafe;

import java.util.ArrayList;

public class TestThreadSafe {
    static final int THREAD_NUMBER = 2;
    static final int LOOP_NUMBER = 200;
    public static void main(String[] args) {
//        ThreadUnsafe test = new ThreadUnsafe();
//        ThreadSafe test = new ThreadSafe();
        ThreadSafeSubClass test = new ThreadSafeSubClass();
        for (int i =0;i<THREAD_NUMBER;i++){
            new Thread(()->{
                test.method1(LOOP_NUMBER);
            },"thread"+(i+1)).start();
        }
    }
}

class ThreadUnsafe{
    ArrayList<String> arrayList = new ArrayList<>();
    public void method1(int loopNum){
        for (int i = 0; i < loopNum; i++) {
            method2();
            method3();
        }
    }
    private void method2() {
        arrayList.add("1");
    }
    private void method3() {
        arrayList.remove(0);
    }
}

class ThreadSafe{
    public void method1(int loopNum){
        ArrayList<String> arrayList = new ArrayList<>();
        for (int i = 0; i < loopNum; i++) {
            method2(arrayList);
            method3(arrayList);
        }
    }
    public void method2(ArrayList<String> arrayList) {
        arrayList.add("1");
    }
    public void method3(ArrayList<String> arrayList) {
        arrayList.remove(0);
    }
}
class ThreadSafeSubClass extends ThreadSafe{
    @Override
    public void method3(ArrayList<String> list) {
        new Thread(() -> {
            list.remove(0);
        }).start();
    }
}